import type { TableColumnCtx } from 'element-plus'

/**
 * 虚拟滚动处理
 * @param data 完整数据
 * @param page 当前页码
 * @param limit 每页条数
 * @returns 当前页数据
 */
export const getVisibleData = (
  data: any[],
  page: number,
  limit: number
): any[] => {
  if (!data || data.length === 0) return []
  const start = (page - 1) * limit
  return data.slice(start, start + limit)
}

/**
 * 生成大量随机测试数据
 * @param count 数据量
 * @returns 测试数据数组
 */
export const generateMockData = (count: number) => {
  const data = []

  for (let i = 0; i < count; i++) {
    data.push({
      id: i + 1,
      name: `LZM ${i + 1}`,
      age: Math.floor(Math.random() * 50) + 18,
      address: `成都市 ${Math.floor(i / 5) + 1}`,
      department: `研发部 ${Math.floor(i / 10) + 1}`,
      position: `全栈工程师 ${Math.floor(i / 3) + 1}`,
      salary: Math.floor(Math.random() * 10000) + 5000,
      email: `user${i + 1}@qq.com`,
      phone: `13${Math.floor(Math.random() * 10000000000)
        .toString()
        .padStart(9, '0')}`,
      date: new Date(
        Date.now() - Math.floor(Math.random() * 1000 * 3600 * 24 * 365)
      )
        .toISOString()
        .split('T')[0],
    })
  }

  return data
}

/**
 * 生成特定结构的测试数据，专门用于展示合并效果
 * @returns 适合测试合并功能的数据
 */
export const generateMergeTestData = () => {
  return [
    {
      id: 1,
      name: '张三',
      age: 28,
      department: '研发部',
      position: '前端工程师',
      salary: 15000,
      email: 'zhangsan@example.com',
      phone: '13511112222',
      address: '北京市朝阳区',
      date: '2022-06-15',
    },
    {
      id: 2,
      name: '李四',
      age: 32,
      department: '研发部',
      position: '前端工程师',
      salary: 16000,
      email: 'lisi@example.com',
      phone: '13522223333',
      address: '北京市海淀区',
      date: '2022-07-20',
    },
    {
      id: 3,
      name: '王五',
      age: 27,
      department: '研发部',
      position: '后端工程师',
      salary: 17000,
      email: 'wangwu@example.com',
      phone: '13533334444',
      address: '上海市浦东新区',
      date: '2022-05-10',
    },
    {
      id: 4,
      name: '赵六',
      age: 30,
      department: '研发部',
      position: '后端工程师',
      salary: 16500,
      email: 'zhaoliu@example.com',
      phone: '13544445555',
      address: '上海市静安区',
      date: '2022-08-05',
    },
    {
      id: 5,
      name: '钱七',
      age: 25,
      department: '设计部',
      position: 'UI设计师',
      salary: 13000,
      email: 'qianqi@example.com',
      phone: '13555556666',
      address: '广州市天河区',
      date: '2022-09-12',
    },
    {
      id: 6,
      name: '孙八',
      age: 26,
      department: '设计部',
      position: 'UI设计师',
      salary: 13500,
      email: 'sunba@example.com',
      phone: '13566667777',
      address: '广州市越秀区',
      date: '2022-04-25',
    },
    {
      id: 7,
      name: '周九',
      age: 28,
      department: '设计部',
      position: 'UX设计师',
      salary: 14000,
      email: 'zhoujiu@example.com',
      phone: '13577778888',
      address: '深圳市南山区',
      date: '2022-03-18',
    },
    {
      id: 8,
      name: '吴十',
      age: 29,
      department: '市场部',
      position: '市场经理',
      salary: 18000,
      email: 'wushi@example.com',
      phone: '13588889999',
      address: '深圳市福田区',
      date: '2022-02-08',
    },
    {
      id: 9,
      name: '郑十一',
      age: 31,
      department: '市场部',
      position: '市场专员',
      salary: 12000,
      email: 'zhengshiyi@example.com',
      phone: '13599990000',
      address: '杭州市西湖区',
      date: '2022-01-15',
    },
    {
      id: 10,
      name: '王十二',
      age: 33,
      department: '市场部',
      position: '市场专员',
      salary: 12500,
      email: 'wangshier@example.com',
      phone: '13500001111',
      address: '杭州市滨江区',
      date: '2022-11-20',
    },
    {
      id: 11,
      name: '刘十三',
      age: 30,
      department: '人事部',
      position: '人事经理',
      salary: 16000,
      email: 'liushisan@example.com',
      phone: '13511112222',
      address: '南京市鼓楼区',
      date: '2022-10-05',
    },
    {
      id: 12,
      name: '陈十四',
      age: 28,
      department: '人事部',
      position: '人事专员',
      salary: 11000,
      email: 'chenshisi@example.com',
      phone: '13522223333',
      address: '南京市玄武区',
      date: '2022-12-10',
    },
  ]
}

/**
 * 生成同时包含部门重复和职位重复的测试数据
 * @returns 适合测试列合并的数据
 */
export const generateColumnMergeTestData = () => {
  return [
    {
      id: 1,
      name: '张三',
      age: 28,
      department: '技术中心',
      position: '技术中心',
      salary: 15000,
      email: 'zhangsan@example.com',
      phone: '13511112222',
      address: '北京市朝阳区',
      date: '2022-06-15',
    },
    {
      id: 2,
      name: '李四',
      age: 32,
      department: '研发部',
      position: '研发部',
      salary: 16000,
      email: 'lisi@example.com',
      phone: '13522223333',
      address: '北京市海淀区',
      date: '2022-07-20',
    },
    {
      id: 3,
      name: '王五',
      age: 27,
      department: '研发部',
      position: '后端工程师',
      salary: 17000,
      email: 'wangwu@example.com',
      phone: '13533334444',
      address: '上海市浦东新区',
      date: '2022-05-10',
    },
    {
      id: 4,
      name: '赵六',
      age: 30,
      department: '设计部',
      position: '设计部',
      salary: 16500,
      email: 'zhaoliu@example.com',
      phone: '13544445555',
      address: '上海市静安区',
      date: '2022-08-05',
    },
    {
      id: 5,
      name: '钱七',
      age: 25,
      department: '设计部',
      position: '设计部',
      salary: 13000,
      email: 'qianqi@example.com',
      phone: '13555556666',
      address: '广州市天河区',
      date: '2022-09-12',
    },
  ]
}

/**
 * 验证规则示例
 */
export const validationRules = {
  name: {
    pattern: /^[a-zA-Z\s]{2,30}$/,
    message: '姓名必须是2-30个英文字符',
  },
  email: {
    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    message: '请输入有效的邮箱地址',
  },
  phone: {
    pattern: /^1[3-9]\d{9}$/,
    message: '请输入有效的手机号码',
  },
  age: {
    pattern: /^(?:1[8-9]|[2-9]\d|100)$/,
    message: '年龄必须在18-100之间',
  },
}

/**
 * 终极简单的行合并方法
 * @param field 合并依据的字段
 * @returns 合并函数
 */
export const finalRowMerge = (field: string) => {
  // 存储每种值的起始行和跨度
  const spanInfo: Record<string, { start: number; span: number }> = {}

  return ({ data, row, rowIndex, columnIndex }: any) => {
    // 如果不是指定字段列，不合并
    if (
      columnIndex !==
      data[0].findIndex((item: any) => item[field] !== undefined)
    ) {
      return [1, 1]
    }

    // 第一行时，初始化spanInfo
    if (rowIndex === 0) {
      const allValues = data.map((item: any) => item[field])
      let currentStart = 0

      for (let i = 0; i < allValues.length; i++) {
        const currentValue = allValues[i]

        // 如果是新的值或者到了末尾
        if (i === allValues.length - 1 || currentValue !== allValues[i + 1]) {
          spanInfo[currentValue] = {
            start: currentStart,
            span: i - currentStart + 1,
          }
          currentStart = i + 1
        }
      }
    }

    // 获取当前值
    const currentValue = row[field]
    const info = spanInfo[currentValue]

    // 如果是该值的起始行，显示并合并
    if (info && info.start === rowIndex) {
      return [info.span, 1]
    } else {
      // 否则隐藏
      return [0, 0]
    }
  }
}

/**
 * 终极简单的列合并方法
 * @param fields 要合并的字段列表
 * @returns 合并函数
 */
export const finalColMerge = (fields: string[]) => {
  return ({ row, columnIndex }: any) => {
    // 只处理在fields中的列
    const fieldIndex = fields.findIndex(
      (f) => columnIndex === Object.keys(row).indexOf(f)
    )
    if (fieldIndex === -1) {
      return [1, 1]
    }

    // 第一个字段不合并
    if (fieldIndex === 0) {
      return [1, 1]
    }

    // 获取当前字段和前一个字段
    const currentField = fields[fieldIndex]
    const prevField = fields[fieldIndex - 1]

    // 如果当前字段值与前一个字段相同，合并
    if (row[currentField] === row[prevField]) {
      return [1, 0]
    }

    return [1, 1]
  }
}

/**
 * 终极简单的行列同时合并方法
 * @param rowField 行合并依据字段
 * @param colFields 列合并依据字段列表
 * @returns 合并函数
 */
export const finalBothMerge = (rowField: string, colFields: string[]) => {
  // 创建行合并和列合并方法
  const rowMergeMap = new Map<string, { start: number; span: number }>()

  return (params: any) => {
    const { data, row, rowIndex, columnIndex } = params

    // 先判断是否要处理行合并
    const targetColIndex = data[0].findIndex(
      (item: any) => item[rowField] !== undefined
    )
    if (columnIndex === targetColIndex) {
      // 第一行时计算所有合并信息
      if (rowIndex === 0) {
        rowMergeMap.clear()
        let start = 0
        let currentValue = data[0][rowField]

        for (let i = 1; i <= data.length; i++) {
          // 到达末尾或值变化
          if (i === data.length || data[i][rowField] !== currentValue) {
            rowMergeMap.set(`${currentValue}-${start}`, {
              start,
              span: i - start,
            })

            if (i < data.length) {
              start = i
              currentValue = data[i][rowField]
            }
          }
        }
      }

      // 查找当前行是否是某个区域的起始行
      const value = row[rowField]
      const key = `${value}-${rowIndex}`

      if (rowMergeMap.has(key)) {
        const info = rowMergeMap.get(key)!
        return [info.span, 1]
      }

      // 如果不是起始行，隐藏
      for (const [k, info] of rowMergeMap.entries()) {
        if (
          k.startsWith(`${value}-`) &&
          rowIndex >= info.start &&
          rowIndex < info.start + info.span
        ) {
          return [0, 0]
        }
      }

      return [1, 1]
    }

    // 处理列合并
    const fieldIndex = colFields.findIndex(
      (f) => columnIndex === Object.keys(row).indexOf(f)
    )
    if (fieldIndex > 0) {
      const currentField = colFields[fieldIndex]
      const prevField = colFields[fieldIndex - 1]

      if (row[currentField] === row[prevField]) {
        return [1, 0]
      }
    }

    return [1, 1]
  }
}
